/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.service.evaluation;

import cn.ac.nercis.pes.model.dto.common.Result;
import cn.ac.nercis.pes.model.dto.common.ResultCode;
import cn.ac.nercis.pes.model.dto.evaluation.analyze.ProblemSuggestDTO;
import cn.ac.nercis.pes.repository.dal.evaluation.ProblemSuggestRepository;
import cn.ac.nercis.pes.repository.dal.evaluation.UnitRiskAnalysisRepository;
import cn.ac.nercis.pes.repository.mapper.evaluation.ProblemSuggestMapper;
import cn.ac.nercis.pes.repository.model.evaluation.ProblemSuggestDO;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 安全问题及改进建议信息服务
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Service
public class ProblemSuggestService {

    private final ProblemSuggestRepository problemSuggestRepository;
    private final UnitRiskAnalysisRepository riskAnalysisRepository;

    @Autowired
    public ProblemSuggestService(ProblemSuggestRepository problemSuggestRepository,
                                 UnitRiskAnalysisRepository riskAnalysisRepository) {
        this.problemSuggestRepository = problemSuggestRepository;
        this.riskAnalysisRepository = riskAnalysisRepository;
    }

    public List<ProblemSuggestDTO> findProblemSuggest(@NonNull String systemId, @NonNull String layerTargetId){
        List<ProblemSuggestDO> problemSuggests = this.problemSuggestRepository.findAllBySystemIdAndLayerTargetIdOrderBySort(systemId,layerTargetId);
        if(CollectionUtils.isEmpty(problemSuggests)){
            this.generateDefaultProblemSuggest(systemId,layerTargetId);
            problemSuggests = this.problemSuggestRepository.findAllBySystemIdAndLayerTargetIdOrderBySort(systemId,layerTargetId);
        }
        return problemSuggests.stream()
                .map(ProblemSuggestMapper.INSTANCE::toDTO)
                .collect(Collectors.toList());
    }

    public Result<ProblemSuggestDTO> saveProblemSuggest(ProblemSuggestDTO problemMeasure){
        if(StringUtils.isEmpty(problemMeasure.getProblem())){
            problemMeasure.setProblem("");
        }
        if(StringUtils.isEmpty(problemMeasure.getSuggest())){
            problemMeasure.setSuggest("");
        }
        try{
            if(StringUtils.isEmpty(problemMeasure.getId())){
                return create(problemMeasure);
            }else{
                return modify(problemMeasure);
            }
        }catch (Exception e){
            log.error("保存安全问题及改进建议信息出错：",e);
            return Result.failed();
        }
    }

    public Result<String> deleteProblemSuggest(String id){
        try{
            return this.problemSuggestRepository.findById(id)
                    .map(entity -> {
                        problemSuggestRepository.delete(entity);
                        return entity;
                    })
                    .map(ProblemSuggestDO::getId)
                    .map(Result::success)
                    .orElse(Result.failed());
        }catch (Exception ex){
            log.error("删除安全问题及改进建议信息出错：",ex);
            return Result.failed();
        }
    }

    private void generateDefaultProblemSuggest(String systemId,String layerTargetId){
        var riskAnalysis = riskAnalysisRepository.findAllBySystemIdAndLayerTargetId(systemId,layerTargetId);
        int initSort = 1;
        List<ProblemSuggestDO> problemSuggests = new ArrayList<>();
        for(var ra:riskAnalysis){
            if(problemSuggests.stream()
                    .anyMatch(ps-> StringUtils.equals(ps.getProblem(),ra.getProblem())
                            && StringUtils.equals(ps.getSuggest(),ra.getSuggest()))){
                continue;
            }
            ProblemSuggestDO ps = ProblemSuggestDO.builder()
                    .systemId(ra.getSystemId())
                    .layerTargetId(ra.getLayerTargetId())
                    .problem(ra.getProblem())
                    .suggest(ra.getSuggest())
                    .sort(initSort)
                    .build();
            ps.setCreateTime(LocalDateTime.now());
            problemSuggests.add(ps);
            initSort++;
        }
        if(CollectionUtils.isNotEmpty(problemSuggests)){
            problemSuggestRepository.saveAll(problemSuggests);
        }
    }

    private Result<ProblemSuggestDTO> create(ProblemSuggestDTO problemSuggest){
        int maxSort = getMaxSort(problemSuggest.getSystemId(),problemSuggest.getLayerTargetId());
        return Optional.of(ProblemSuggestMapper.INSTANCE.toDO(problemSuggest))
                .map(e->{
                    e.setSort(maxSort+1);
                    e.setCreateTime(LocalDateTime.now());
                    return e;
                })
                .map(problemSuggestRepository::save)
                .map(ProblemSuggestMapper.INSTANCE::toDTO)
                .map(Result::success)
                .orElse(Result.failed());
    }

    private Result<ProblemSuggestDTO> modify(ProblemSuggestDTO problemSuggest){
        ProblemSuggestDO source = this.problemSuggestRepository.findById(problemSuggest.getId()).orElse(null);
        if(Objects.isNull(source)){
            return Result.failed(ResultCode.NOT_FOUND);
        }
        return Optional.of(source)
                .map(s->{
                    s.setProblem(problemSuggest.getProblem());
                    s.setSuggest(problemSuggest.getSuggest());
                    s.setModifyTime(LocalDateTime.now());
                    return s;
                })
                .map(problemSuggestRepository::save)
                .map(ProblemSuggestMapper.INSTANCE::toDTO)
                .map(Result::success)
                .orElse(Result.failed(ResultCode.FAIL));
    }

    private Integer getMaxSort(String systemId,String layerTargetId){
        return problemSuggestRepository.findAllBySystemIdAndLayerTargetIdOrderBySort(systemId,layerTargetId)
                .stream()
                .mapToInt(ProblemSuggestDO::getSort)
                .max()
                .orElse(0);
    }
}